package com.sphd.emanu.activity.sale;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.todaysale.TodaysaleActivity;
import com.sphd.emanu.adapter.SaleAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.DaySale;
import com.sphd.emanu.pojo.MonthSale;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.TimePickerDialog;
import com.wzutils.TimeUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 销售额 查看 此界面和查询界面共用 用type来区分
 *  查询年月日共用界面 不跳转只刷新list
 * @Author Hu
 * @Time 2017/4/1 -- 17:41.
 * @Email 87683202@qq.com
 */

public class Salectivity extends MVPBaseActivity<SaleContract.View, SalePresenter> implements SaleContract.View, TimePickerDialog.TimePickerDialogInterface {
    Intent intent;
    Bundle bundle;
    int TYPE = 0;//区分是查询还是月份展示
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.open_time)
    TextView openTime;
    @BindView(R.id.layout_open_time)
    LinearLayout layoutOpenTime;
    @BindView(R.id.over_time)
    TextView overTime;
    @BindView(R.id.layout_over_time)
    LinearLayout layoutOverTime;
    @BindView(R.id.btn_search)
    TextView btnSearch;
    @BindView(R.id.layout_search)
    LinearLayout layoutSearch;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    SaleAdapter saleAdapter;
    User user;
    @BindView(R.id.month_sale)
    TextView monthSaleTV;
    @BindView(R.id.month_sale_topup)
    TextView monthSaleTopup;
    TimePickerDialog mTimePickerDialog;
    int flag = 0;//开始和结束时间的选取标志
    String opentimeString, overtimeString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sale);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mySwf.setOnRefreshListener(() -> {
                    if (TYPE == 1) {
                        addData();
                    } else {
                        searchAddData();
                    }
                }
        );

        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                DaySale daySale = (DaySale) adapter.getItem(position);
                String date = daySale.getDate();
                String[] firstAndLast = null;
                if (date.length() == 4) {
                    //年
                    firstAndLast = TimeUtils.getYearFirstLastDay(Calendar.getInstance(), TimeUtils.stringTolong(date + "-01-01 00:00:00",
                            TimeUtils.YEAR_MONTH_DAY_HOUR_MIN_SS));
                    opentimeString = firstAndLast[0] + Constant.HH_MM_SS;
                    overtimeString = firstAndLast[1] + Constant.HH_MM_SS;
                    searchAddData();
                } else if (date.length() == 7) {
                    //月
                    try {
                        firstAndLast = TimeUtils.getNowMonthFirstLastday(Calendar.getInstance(), TimeUtils.stringTolong(date + "-01 00:00:00",
                                TimeUtils.YEAR_MONTH_DAY_HOUR_MIN_SS));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    opentimeString = firstAndLast[0] + Constant.HH_MM_SS;
                    overtimeString = firstAndLast[1] + Constant.HH_MM_SS;
                    searchAddData();
                } else if (date.length() == 10) {
                    bundle.putString(Constant.DAY_SALE, daySale.getDate() + Constant.HH_MM_SS);
                    intent.putExtras(bundle);
                    intent.setClass(context, TodaysaleActivity.class);
                    startActivity(intent);
                }


            }
        });
    }

    private void searchAddData() {
        showProgressDialog();
        mPresenter.selectSale(user.getOid(), opentimeString,overtimeString);

    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        TYPE = bundle.getInt(Constant.TYPE);
        mTimePickerDialog = new TimePickerDialog(this);
        initLayout();
        initAdapter();
    }

    private void addData() {
        showProgressDialog();
        mPresenter.saleMonthSum(user.getOid());
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecycler);
        saleAdapter = new SaleAdapter(R.layout.item_sale, new ArrayList<DaySale>());
        saleAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(saleAdapter);
    }

    /**
     * 0、表示查询 1、本月
     */
    private void initLayout() {
        if (TYPE == 0) {
            layoutSearch.setVisibility(View.VISIBLE);
            setTitleBar(toolbar, "销售额查询");
        } else {
            layoutSearch.setVisibility(View.GONE);
            setTitleBar(toolbar, "本月销售额");
            addData();
        }
    }

    @Override
    public void recBean(MonthSale monthSale) {
        dissProgressDialog();
        monthSaleTV.setText(monthSale.getMonthSaleSum().toString());
        monthSaleTopup.setText(monthSale.getMonthDepositSum().toString());
        saleAdapter.setNewData(monthSale.getList());
    }

    @OnClick({R.id.layout_open_time, R.id.layout_over_time, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_open_time:
                flag = 0;
                mTimePickerDialog.showDateAndTimePickerDialog();
                break;
            case R.id.layout_over_time:
                flag = 1;
                mTimePickerDialog.showDateAndTimePickerDialog();
                break;
            case R.id.btn_search:
                if ("点击选择".equals(getText(openTime)) || "点击选择".equals(getText(overTime))) {
                    toast("请选择正确的开始和结束时间后进行查询。");
                } else {
                    if (getText(openTime).equals(getText(overTime))) {
                        saleAdapter.setNewData(null);
                        monthSaleTV.setText("");
                        monthSaleTopup.setText("");
                        bundle.putString(Constant.DAY_SALE, getText(openTime) + Constant.HH_MM_SS);
                        intent.putExtras(bundle);
                        intent.setClass(context, TodaysaleActivity.class);
                        startActivity(intent);
                    } else {
                        opentimeString = getText(openTime) + Constant.HH_MM_SS;
                        overtimeString = getText(overTime) + Constant.HH_MM_SS;
                        searchAddData();
                    }
                }

                break;
        }
    }

    @Override
    public void positiveListener() {
        String year = String.valueOf(mTimePickerDialog.getYear());
        String month = mTimePickerDialog.getMonth() < 10 ? ("0" + mTimePickerDialog.getMonth()) : String.valueOf(mTimePickerDialog.getMonth());
        String day = mTimePickerDialog.getDay() < 10 ? ("0" + mTimePickerDialog.getDay()) : String.valueOf(mTimePickerDialog.getDay());
        String hour = mTimePickerDialog.getHour() < 10 ? ("0" + mTimePickerDialog.getHour()) : String.valueOf(mTimePickerDialog.getHour());
        String minute = mTimePickerDialog.getMinute() < 10 ? ("0" + mTimePickerDialog.getMinute()) : String.valueOf(mTimePickerDialog.getMinute());
        checkTime(year, month, day, flag == 0 ? openTime : overTime);

    }

    private String getText(TextView textView) {
        return textView.getText().toString().trim();
    }

    private void checkTime(String year, String month, String day, TextView timeTv) {
        if ("点击选择".equals(flag == 0 ? getText(overTime) : getText(openTime))) {
            timeTv.setText(year + "-" + month + "-" + day);
        } else {
            int compare;
            if (flag == 0) {
                compare = TimeUtils.compare_date(
                        ((year + "-" + month + "-" + day)), getText(overTime));
            } else {
                compare = TimeUtils.compare_date(getText(openTime),
                        ((year + "-" + month + "-" + day)));
            }
            if (compare == 1 || compare == 0) {
                timeTv.setText(year + "-" + month + "-" + day);
            } else if (compare == -1) {
                toast(flag == 0 ? "开始时间不能晚于结束时间" : "结束时间不能早于开始时间");
            } else if (compare == -2) {
                toast("时间选择错误，请稍后重试。");
            }
        }
    }

    @Override
    public void negativeListener() {

    }
}
